package com.competitions.easydubbing.service.impl;

import com.competitions.easydubbing.entity.Result;
import com.competitions.easydubbing.service.VideoProcessService;
import com.competitions.easydubbing.util.StreamUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Random;

/**
 * @author Mapler
 */
@Service
public class VideoProcessServiceImpl implements VideoProcessService {
    @Override
    public ResponseEntity<Result> processVideo(MultipartFile video, int uid){
        String basePath = "C:\\uploadFiles\\";
        String videoPath = basePath+"videos\\"+System.currentTimeMillis()+".mp4";
        File videoFile = new File(videoPath);
        try {
            video.transferTo(videoFile);
            Random random = new Random();
            String audio = "C:\\example\\example"+ (random.nextInt(2)+1)+ ".mp3";
            String command = "ffmpeg -i " + audio + " -i " +videoPath+" -filter_complex amix=inputs=2:duration=shortest:dropout_transition=2 "+videoPath.replace(".mp4","withBg.mp4");
            Process process = Runtime.getRuntime().exec(command);
            StreamUtil.dealStream(process);
            process.waitFor();
            videoFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Result.error("failed"));
        }
        return ResponseEntity.ok().body(Result.ok("success",videoPath.replace("C:\\uploadFiles\\videos\\","http://47.102.150.68:8066/upload/videos/").replace(".mp4","withBg.mp4")));
    }
}
